package model

import (
	"encoding/base64"
	"fmt"
	"strings"

	"mall/common/errorx"
)

func EncodeID(modelName string, databaseId int64, splitter string) string {
	key := fmt.Sprintf("%s%s%v", modelName, splitter, databaseId)
	return base64.RawURLEncoding.EncodeToString([]byte(key))
}

func DecodeID(modelName string, ID string, splitter string) (string, error) {
	bytes, err := base64.RawURLEncoding.DecodeString(ID)
	if err != nil {
		return "0", err
	}

	arrStr := strings.Split(string(bytes), splitter)
	if len(arrStr) != 2 || arrStr[0] != modelName {
		err = errorx.NewDefaultError("ID is invalid")
		return "0", err
	}

	return arrStr[1], nil
}
